package com.example.flashsales.Tools;
import com.example.flashsales.Factory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
//    private static RedisUtils redisUtils;
//    public static synchronized RedisUtils getRedis(){
//        if (redisUtils == null){
//            synchronized (RedisUtils.class){
//                if (redisUtils == null){
//                    redisUtils = new RedisUtils();
//                }
//            }
//        }
//        return redisUtils;
//    }


    /**
     * 初始化redis
     */
    @PostConstruct
    private void Initialize(){
        final Object das = this.get("user");
        if (das == null){
            this.set("user",new HashMap<>());
        }
        this.getAndSet("user",new HashMap<>());
    }







    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final Object key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存
     */
    public boolean set(final Object key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public boolean getAndSet(final Object key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public boolean delete(final Object key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
